#include "texture.hh"

#include <iostream>

SDL_Surface*
rotate_img (SDL_Surface* s)
{
  SDL_Surface* res = SDL_CreateRGBSurface (SDL_SWSURFACE,
					   s->w, s->h,
					   s->format->BitsPerPixel,
					   s->format->Rmask,
					   s->format->Gmask,
					   s->format->Bmask,
					   s->format->Amask);

  SDL_LockSurface (s);
  SDL_LockSurface (res);

  for (int i = 0; i < s->h; ++i)
  {
    memcpy (&((unsigned char*) res->pixels)[i * s->pitch],
	    &((unsigned char*) s->pixels)[(s->h - 1 - i) * s->pitch],
	    s->pitch);
  }

  SDL_UnlockSurface (res);
  SDL_UnlockSurface (s);

  return res;
}

Texture::Texture (const std::string& path)
{
  SDL_Surface* img = SDL_LoadBMP (path.c_str ());

  if (!img)
  {
    std::cout << "Cannot create texture, " << path << " not found" << std::endl;
    exit (1);
  }

  unsigned rmask, gmask, bmask, amask;

#if SDL_BYTEORDER == SDL_BIG_ENDIAN

  rmask = 0xff000000;
  gmask = 0x00ff0000;
  bmask = 0x0000ff00;
  amask = 0x000000ff;

#else

  rmask = 0x000000ff;
  gmask = 0X0000ff00;
  bmask = 0x00ff0000;
  amask = 0Xff000000;

#endif

  SDL_PixelFormat f = *(img->format);
  f.BitsPerPixel = 32;
  f.BytesPerPixel = 4;
  f.Rmask = rmask;
  f.Gmask = gmask;
  f.Bmask = bmask;
  f.Amask = amask;

  SDL_Surface* res = SDL_ConvertSurface (img, &f, SDL_SWSURFACE);
  img_ = rotate_img (res);
  glGenTextures (1, &id_);


  glBindTexture (GL_TEXTURE_2D, id_);

  gluBuild2DMipmaps (GL_TEXTURE_2D, 4,
		     img_->w, img_->h,
		     GL_RGBA, GL_UNSIGNED_BYTE,
		     img_->pixels);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

  SDL_FreeSurface (img);
  SDL_FreeSurface (res);
}
